package com.pocket.insight.service.impl;

import com.pocket.insight.base.exception.BizException;
import com.pocket.insight.entity.App;
import com.pocket.insight.mapper.AppMapper;
import com.pocket.insight.service.AppService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * 应用服务实现类
 */
@Slf4j
@Service
public class AppServiceImpl implements AppService {

    @Resource private AppMapper appMapper;

    @Override
    public App save(App app) {
        // 设置基础信息
        app.setCreatedAt(LocalDateTime.now());
        app.setUpdatedAt(LocalDateTime.now());
        app.setIsDelete(false);
        app.setIsPublish(false);
        app.setVisible(true);
        app.setAccessCount(0L);
        
        // 设置默认选项
        if (app.getOptions() == null) {
            app.setOptions(new App.Options());
        }
        appMapper.insert(app);
        return app;
    }

    @Override
    public List<App> list() {
        return appMapper.selectList(new App());
    }

    @Override
    public void delete(Long id) {
        App app = getById(id);
        if (app == null) {
            throw new BizException("应用不存在");
        }
        app.setIsDelete(true);
        app.setUpdatedAt(LocalDateTime.now());
        appMapper.updateByPrimaryKey(app);
    }

    @Override
    public App getById(Long id) {
        return appMapper.selectByPrimaryKey(id).orElseGet(null);
    }

    @Override
    public App update(App app) {
        App existApp = getById(app.getId());
        if (existApp == null) {
            throw new BizException("应用不存在");
        }
        app.setUpdatedAt(LocalDateTime.now());
        appMapper.updateByPrimaryKey(app);
        return app;
    }

    @Override
    public App publish(Long id) {
        App app = getById(id);
        if (app == null) {
            throw new BizException("应用不存在");
        }
        app.setIsPublish(true);
        app.setPublishHash(UUID.randomUUID().toString());
        app.setPublishedBy(getCurrentUserId());
        app.setLatestPublishedAt(LocalDateTime.now());
        app.setUpdatedAt(LocalDateTime.now());
        appMapper.updateByPrimaryKey(app);
        return app;
    }

    @Override
    public App unpublish(Long id) {
        App app = getById(id);
        if (app == null) {
            throw new BizException("应用不存在");
        }
        app.setIsPublish(false);
        app.setUpdatedAt(LocalDateTime.now());
        appMapper.updateByPrimaryKey(app);
        return app;
    }

    /**
     * 获取当前用户ID
     */
    private Long getCurrentUserId() {
        // TODO: 实现获取当前登录用户ID的逻辑
        return 1L;
    }
} 